function changecomName() {
	$("#communityAddress").val("");
	$("#total").val("");
}

function addComListBox(callback, name) {
	var comNameNode = $("#" + name).eq(0), addListBox = new YW.widget.AddListBox({
		nameField : name,
		primaryKey : "tmpId",
		clickFilter : false,
		searchLength : 10000,
		searchNode : comNameNode,
		clickCallBack : function(clicknode) {
			var data = $(clicknode.node).data("data");
			if (data && data[name]) {
				comNameNode.data("data", data);
				if ($.isFunction(callback)) {
					callback(data);
				}
				comNameNode.change();
				if ($.isFunction(callback)) {
					callback(data);
				}
			}
		}
	}), listBox = addListBox.getNode().listBox;
	$("#Popup-box .box-listBox").append(listBox);
	comNameNode.bind("blur", function() {
		setTimeout(function() {
			$("#Popup-box").css({
				"display" : "none"
			});
		}, 300);
	});
	return {
		addListBox : addListBox,
		listBox : listBox
	};
}

$(function() {
	var addListBoxObj = addComListBox(function(data) {
		$("#comName").val(data['comName']);
		$("#selectCid").val(data['cid']);
		$("#communityAddress").val(data['plotAddr']);
		$("#total").val(data['total']);
	}, "comName");
	var addListBox = addListBoxObj.addListBox;
	var listBox = addListBoxObj.listBox;

	$("a[rel^='prettyPhoto']").prettyPhoto();

	if (_result != null && _result.communityVettedId != null) {
		var _city = _result.cityId;
		var _proId = _result.proId;
		var initUrl = '/IMS/companycheck/searchByCode.ht';
		$.ajax({
			type : 'post',
			async : false,
			data : {
				provinceCode : _proId,
				cityCode : _city
			},
			url : initUrl,
			dataType : 'json',
			success : function(value) {
				var code = value.code;
				addListBox.setData(value.result, []);
			}
		});
	}

	setValidate($("#frm"), {
		rules : {
			s_city : {
				required : true
			},
			comName : {
				required : true
			},
			communityAddress : {
				required : true
			},
			total : {
				required : true,
				positiveInt : true
			}
		},
		messages : {
			s_city : {
				required : "必填"
			},
			comName : {
				required : "必填"
			},
			communityAddress : {
				required : "必填"
			},
			total : {
				required : "必填"
			}
		}
	});
	initProvinceSeletor(); // 初始化省市区下拉框
	var _cID = _dmsCommunity.cid;
	if (_cID != null && _cID != '' && _cID != undefined) {
		initSelectOrEnterCommunity(); // 初始化小区名称选择和输入
	}

	$("#companySelect2").select2({
		placeholder : "请选择小区"
	});

	$("#s_province option[value='" + curProvince + "']").attr("selected", "selected");
	var _provinceIndex = $("#s_province option:selected").attr("index");

	if (_provinceIndex && _provinceCache[_provinceIndex]) {
		initCitySelector(_provinceCache[_provinceIndex].children);
	}
	$("#s_city option[value='" + curCity + "']").attr("selected", "selected");
	var _cityIndex = $("#s_city option:selected").attr("index");
	if (_cityIndex)
		initAreaSelector(_provinceCache[_provinceIndex].children[_cityIndex].children);
	else
		initAreaSelector(null);
	$("#s_area option[value='" + curArea + "']").attr("selected", "selected");

	$("#s_province").change(function() {
		var index = $(this).children("option:selected").attr("index");
		if (index) {
			initCitySelector(_provinceCache[index].children);
		} else {
			initCitySelector(null);
		}

		$("#areaCodes").val($(this).val());

	});

	$("#s_city").change(function() {
		var p_index = $("#s_province").children("option:selected").attr("index");
		var index = $(this).children("option:selected").attr("index");
		if (p_index >= 0 && index >= 0) {
			initAreaSelector(_provinceCache[p_index].children[index].children);
		} else {
			initAreaSelector(null);
		}

		$("#areaCodes").val($("#s_province").val() + "," + $(this).val());

	});

	$("#s_area").change(function() {
		$("#areaCodes").val($("#s_province").val() + "," + $("#s_city").val() + "," + $(this).val());

	});

	// 城市下拉绑定事件
	$("#div_city").change(function() {
		var province = $("#s_province").val();
		var city = $("#s_city").val();
		var url = '/IMS/companycheck/searchByCode.ht';
		$.ajax({
			type : 'post',
			async : true,
			data : {
				provinceCode : province,
				cityCode : city
			},
			url : url,
			dataType : 'json',
			beforeSend : function() {
				showProccessBar();
			},
			error : function() {
				hideProccessBar();
			},
			success : function(value) {
				var code = value.code;
				$("#selectCid").val("");
				$("#communityAddress").val("");
				$("#comName").val("");
				$("#total").val("");

				$(listBox).empty();
				addListBox.setData([], []);
				addListBox.setData(value.result, []);
				hideProccessBar();
			},
			error : function(value, a, b) {
				return;
			}
		});
	});

	var contractArray = new Array();
	if (contract) {
		contractArray = contract.split(",");
		for (var i = 0; i < contractArray.length; i++) {
			var btn1 = "uploadifyButton" + (i + 1);
			if (contractArray.length == 1) {
				$("#btn2").show();
			} else {
				if (i > 0) {
					$("#btn" + (i + 1)).show();
				}
			}
			if (i == 0) {
				$("#tempFileName").val(contractArray[i]);
			}
			if (i == 1) {
				$("#tempFileName1").val(contractArray[i]);
			}
			if (i == 2) {
				$("#tempFileName3").val(contractArray[i]);
			}
			$("#" + btn1).attr('src',fileServerUrl + contractArray[i]);
			//showUploadTip(fileServerUrl + contractArray[i], btn1);
		}
	}
	
	$("#uploadifyButton2").html5Upload({
		url : '/IMS/fileUpload.ht',
		fileTypeExts : [ '.gif', '.jpg', '.png' ],
		onUploadSuccess : function(data, filename) {
			if(data){
				if(data.code == 1){
					_alert(data.message);
				}else{
					if(data.result){
						$("#btn3").show();
						$("#tempFileName1").val(data.result[0]);
					}
				}
			}
		}
	});
	/*
	$("#uploadifyButton2").uploadify({
		'id' : 'uploadifyButton2',
		'swf' : '/IMS/js/plugins/file/uploadify/uploadify.swf',
		'uploader' : '/IMS/fileUpload.ht',
		'buttonText' : '',
		'fileTypeDesc' : '当前允许上传格式：*.jpg | *.gif | *.png',
		'fileTypeExts' : '*.gif; *.jpg; *.png',
		'queueID' : 'fileQueue2',
		'auto' : true,
		'multi' : false,
		'width' : 270,
		'height' : 200,
		'method' : 'post',
		'fileSizeLimit' : '10MB',
		'onUploadSuccess' : function(fileData, jsonData) {
			var obj;
			if (jsonData) {
				obj = eval('(' + jsonData + ')');
				if (obj.code == 1) {
					_alert(obj.message);
				} else {
					if (obj.result) {
						$("#btn3").show();
						$("#uploadifyButton2-button img").remove();
						$("#uploadifyButton2-button").append("<img src='" + obj.result[0] + "'/>");
						$("#tempFileName1").val(obj.result[0]);
					}
				}
			}
		}
	});
	*/
	
	$("#uploadifyButton1").html5Upload({
		url : '/IMS/fileUpload.ht',
		fileTypeExts : [ '.gif', '.jpg', '.png' ],
		onUploadSuccess : function(data, filename) {
			if(data){
				if(data.code == 1){
					_alert(data.message);
				}else{
					if(data.result){
						$("#btn2").show();
						$("#tempFileName").val(data.result[0]);
					}
				}
			}
		}
	});
	/*
	$("#uploadifyButton1").uploadify({
		'id' : 'uploadifyButton1',
		'swf' : '/IMS/js/plugins/file/uploadify/uploadify.swf',
		'uploader' : '/IMS/fileUpload.ht',
		'buttonText' : '',
		'fileTypeDesc' : 'Image Files',
		'fileTypeExts' : '*.gif; *.jpg; *.png',
		'queueID' : 'fileQueue2',
		'auto' : true,
		'multi' : false,
		'width' : 270,
		'height' : 200,
		'method' : 'post',
		'fileSizeLimit' : '10MB',
		'onUploadSuccess' : function(fileData, jsonData) {
			var obj;
			if (jsonData) {
				obj = eval('(' + jsonData + ')');
				if (obj.code == 1) {
					_alert(obj.message);
				} else {
					if (obj.result) {
						$("#btn2").show();
						$("#uploadifyButton1-button img").remove();
						$("#uploadifyButton1-button").append("<img src='" + obj.result[0] + "'/>");
						$("#tempFileName").val(obj.result[0]);
					}
				}
			}
		}
	});
	*/
	
	$("#uploadifyButton3").html5Upload({
		url : '/IMS/fileUpload.ht',
		fileTypeExts : [ '.gif', '.jpg', '.png' ],
		onUploadSuccess : function(data, filename) {
			if(data){
				if(data.code == 1){
					_alert(data.message);
				}else{
					if(data.result){
						$("#tempFileName3").val(data.result[0]);
					}
				}
			}
		}
	});
	/*
	$("#uploadifyButton3").uploadify({
		'id' : 'uploadifyButton3',
		'swf' : '/IMS/js/plugins/file/uploadify/uploadify.swf',
		'uploader' : '/IMS/fileUpload.ht',
		'buttonText' : '',
		'fileTypeDesc' : '当前允许上传格式：*.jpg | *.gif | *.png',
		'fileTypeExts' : '*.gif; *.jpg; *.png',
		'queueID' : 'fileQueue2',
		'auto' : true,
		'multi' : false,
		'width' : 270,
		'height' : 200,
		'method' : 'post',
		'fileSizeLimit' : '10MB',
		'onUploadSuccess' : function(fileData, jsonData) {
			var obj;
			if (jsonData) {
				obj = eval('(' + jsonData + ')');
				if (obj.code == 1) {
					_alert(obj.message);
				} else {
					if (obj.result) {
						$("#uploadifyButton3-button img").remove();
						$("#uploadifyButton3-button").append("<img src='" + obj.result[0] + "'/>");
						$("#tempFileName3").val(obj.result[0]);
					}
				}
			}
		}
	});
	*/
	
	$("#companyId").select2({
		language : "zh-CN",
		placeholder : '请选择公司',
		ajax : {
			url : '/IMS/select/getCompanyList.ht',
			dataType : 'json',
			delay : 250,
			data : function(param) {
				return {
					search : param.term,
					page : param.page || 1,
					showAllItem : false
				};
			},
			processResults : function(data, param) {
				param.page = data.pageNum;
				return {
					results : data.list,
					pagination : {
						more : data.hasNextPage
					}
				};
			}
		},
		escapeMarkup : function(markup) {
			return markup;
		},
		// minimumInputLength: 1,
		templateResult : formatRepo,
		// 显示查询结果
		templateSelection : function(obj) {
			// $("#select2-companyId-container").html(obj.name || obj.text);
			$("#ht_companyId").val(obj.id);
			$("#companyName").val(obj.name || obj.text);
			// $("#select2-companyId-container").html(obj.name || obj.text);
			return obj.name || obj.text;
		} // 显示选中的对象
	});

	if (companyName) {
		$("#select2-companyId-container").attr("title", companyName);
		$("#select2-companyId-container").html(companyName);
	}

	$("#s_province").select2({
		placeholder : "请选择省份"
	});
	$("#s_city").select2({
		placeholder : "请选择城市"
	});
	$("#s_area").select2({
		placeholder : "请选择区县"
	});
});

function initSelectOrEnterCommunity() {
	var cid = _dmsCommunity.cid;
	if (cid != null && cid != '' && cid != undefined) {
		$("#switchType").val('enter');
		$("#switch").val('点击切换到小区输入');
		$("#enterCommunity").hide();
		$("#selectCommunity").show();
	} else {
		$("#selectCid").val("");
		$("#switchType").val('select');
		$("#switch").val('点击切换到小区选择');
		$("#enterCommunity").show();
		$("#selectCommunity").hide();
		$("#address").val("");
	}
}

function initProvinceSeletor() {
	$("#s_province option").remove();
	var citys;
	$.each(_provinceCache, function(index) {
		var optionDom = "<option value='" + this.code + "' ";
		if (index == 0) {
			optionDom += "selected='" + "seleceted' "
		}
		optionDom += "index=" + index + ">" + this.name + "</option>";
		$("#s_province").append(optionDom);
	});
	initCitySelector(citys);
}

function initCitySelector(citys) {
	$("#s_city option").remove();
	var areas;
	$("#s_city").append("<option value='' selected='selected'>请选择</option>");
	if (citys && citys.length > 0) {
		$.each(citys, function(index) {
			var optionDom = "<option value='" + this.code + "' ";
			optionDom += "index=" + index + ">" + this.name + "</option>";
			$("#s_city").append(optionDom);
		});
	}
	$("#s_city").select2({
		placeholder : "请选择城市"
	});
	initAreaSelector(areas);
}

function initAreaSelector(areas) {
	$("#s_area option").remove();
	$("#s_area").append("<option value='' selected='selected'>请选择</option>");
	if (areas && areas.length > 0) {
		$.each(areas, function(index) {
			var optionDom = "<option value='" + this.code + "'>" + this.name + "</option>";
			$("#s_area").append(optionDom);
		});
	}

	$("#s_area").select2({
		placeholder : "请选择区县"
	});
}

function showSwitch() {
	var switchType = $("#switchType").val();
	if (switchType == 'enter') {
		$("#selectCid").val("");
		$("#switchType").val('select');
		$("#switch").val('点击切换到小区选择');
		$("#enterCommunity").show();
		$("#selectCommunity").hide();
		$("#address").val("");
	} else {
		$("#switchType").val('enter');
		$("#switch").val('点击切换到小区输入');
		$("#enterCommunity").hide();
		$("#selectCommunity").show();
		$("#companySelect2").select2("val", null);
	}

}

/**
 * *初始化hidden区域的值
 */

function resetCidHidden() {
	$("#selectCid").val('');
}

function selectAddressByCid() {
	var code = $("#companySelect2 option:selected").val();
	var idArray = new Array();
	idArray = code.split(',');
	var cid = null;
	if (idArray.length > 3) {
		cid = idArray[0];
		var cName = idArray[0];
		var address = idArray[2];
		var total = idArray[3];
		$("#address").val(address);
		$("total").val(total);
	} else if (idArray.length > 2) {
		cid = idArray[0];
		var address = idArray[2];
		$("#address").val(address);
	} else {
		cid = idArray[0];
	}
	$("#selectCid").val(cid);
}

function saveCommunity() {
	var form = $('#frm');

	if (chkNull("s_city", "请选择城市")) {
		return;
	}

	var _provinceIndex = $("#s_province option:selected").attr("index");
	var _cityIndex = $("#s_city option:selected").attr("index");
	var _region = _provinceCache[_provinceIndex].children[_cityIndex].children;
	if (_region && _region.length > 0) {
		if (chkNull("s_area", "请选择县区")) {
			return;
		}
	}

	if (chkNull("comName", "请输入小区")) {
		return;
	}
	if (chkNull("communityAddress", "请输入小区地址")) {
		return;
	}
	if (chkNull("total", "请输入小区总户数")) {
		return;
	} else {
		var num = /^[1-9][0-9]*$/;
		if (checkReg(num, '总户数请输入正整数', $("#total").val())) {
			return;
		}
	}

	if (chkNull("tempFileName", "请上传图片")) {
		return;
	}
	var cName = $("#comName").val();
	var cityCode = $("#s_city").val();
	var checkUrl = '/IMS/community/searchCommunityinPDS.ht';
	var pcid = $("#companyId").val();
	if ((pcid == null || pcid == "") && (($("#ht_companyId").val() == null || $("#ht_companyId").val() == ""))) {
		_alert("请选择公司");
		return;
	}
	if (pcid == null || pcid == "") {
		pcid = $("#ht_companyId").val();
		$("#companyId").val(pcid);
	}
	if (pcid == null || pcid == "") {
		_alert("请选择公司");
		return;
	}
	var _cid = $('#selectCid').val();

	// checkUrl = checkUrl + "?checkName=" + cName + "&cityCode=" + cityCode + "&selectCid=" + _cid;
	$.ajax({
		type : 'post',
		async : false,
		url : checkUrl,
		contentType: 'application/json;charset=utf-8',
    	data: {"checkName": cName ,"cityCode": cityCode , "selectCid": _cid },
		dataType : 'json',
		beforeSend : function() {
			showProccessBar();
		},
		error : function() {
			hideProccessBar();
		},
		success : function(value) {
			var code = value.code;
			if (code == message_success_code) {
				$.submit(form, {
					dataType : 'json',
					error : function() {
						hideProccessBar();
					},
					success : function(data, textStatus) {
						var code = data.code;
						if (message_success_code == code) {
							var url = '/IMS/community/showList.ht';
							_alert("新增成功，请等待自动刷新", function() {
								$.go(url, {
									dataType : 'html',
									error : function() {
										hideProccessBar();
									},
									success : function(data, textStatus) {
										replaceDocument(url, data);
									}
								});
							});
						} else {
							_alert(data.msg);
							hideProccessBar();
						}
					}
				});
			} else if (code == message_false_code) {
				_alert(value.msg);
				hideProccessBar();
				return;
			} else if (code == '3') {
				var msg = value.msg;

				_confirm("<span style=\"color:#FE6600\">" + msg + "</span>", function() {
					$.submit(form, {
						dataType : 'json',
						error : function() {
							hideProccessBar();
						},
						success : function(data, textStatus) {
							var code = data.code;
							if (message_success_code == code) {
								var url = '/IMS/community/showList.ht';
								$.go(url, {
									dataType : 'html',
									error : function() {
										hideProccessBar();
									},
									success : function(data, textStatus) {
										replaceDocument(url, data);
									}
								});
							} else {
								_alert(data.msg);
								hideProccessBar();
							}
						}
					});
				});
			}
		}
	});
}

function returnBack(url) {
	$.go(url, {
		dataType : 'html',
		beforeSend : function() {
			showProccessBar();
		},
		error : function() {
			hideProccessBar();
		},
		success : function(data, textStatus) {
			replaceDocument(url, data);
		}
	});
}